import { TableSelectionModel } from '@cscec/udp-ui';
import { ITable, getFormItemProps, isNumberType } from '@/components/editor/plugin';
import { getDesignContent } from './service';
import { setTableColumnFormat } from '@/components/editor/util';
import list from '@/pages/customForm/list';

export enum ENUM_TEMPLATE {
  NULL = -1,      //空白模板
  LIST = 0,       //列表页--列表
  TREE_TABLE = 1, //列表页--左树右表
  MAIN = 10,      //详情页--主表
  MASTER_SLAVE_TABLE = 11,    //详情页--主子表
}

//列表页树类型
export enum LIST_TREE_TYPE {
  PROJECT = 'PROJECT',  //项目管理组织树
  ORG = 'ORG',          //组织树
  DEPT = 'DEPT'         //组织部门树
}

//详情页表格展示类型
export enum EDIT_DISPLAY_TYPE {
  TAB = 'TAB',          //Tab页
  PANEL = 'PANEL'       //Panel页
}

function getListTpl(busType: string, mainTable: ITable[], templateInfo: any) {
  const list: ITable[] = mainTable;
  return {
    type: 'list-page',
    masterTableName: list[0]?.tableName,
    showProjectOrgTree: [ENUM_TEMPLATE.TREE_TABLE].includes(+templateInfo.listLayout),
    orgTreeType: templateInfo.listTreeType,
    busType,
    requestList: {
      method: 'get',
      url: '/customForm/customPC/getList'
    },
    requestDelete: {
      method: 'post',
      url: '/customForm/customPC/delete',
      dataType: 'json'
    },
    toolbar: [{
      type: 'tool-bar',
      id: `${busType}_toolbar`,
      buttonType: 'default',
      buttons: [
        {
          itemId: 'add',
          text: '新增',
          itemType: 'primary',
          icon: 'FileAddOutlined'
        },
        {
          itemId: 'edit',
          text: '修改',
          icon: 'EditOutlined'
        },
        {
          itemId: 'delete',
          text: '删除',
          icon: 'DeleteOutlined'
        },
        {
          itemId: 'view',
          text: '查看',
          icon: 'EyeOutlined'
        },
        {
          itemId: 'check',
          text: '送审',
          icon: 'SolutionOutlined'
        },
        {
          itemId: 'applyForReview',
          text: '申请去审',
          icon: 'ExceptionOutlined'
        }
      ]
    }],
    table: [{
      type: 'table',
      id: `${busType}_${list[0]?.tableName}`,
      name: list[0]?.tableName,
      table: list[0]?.tableName,
      columnsTogglable: false,
      columns:
        list.length > 0
          ? list[0].bizColumnDesignQueryVoList
              .filter(({ listShowFlg, showFlg }) => listShowFlg === 1 && showFlg === 1)
              .map((column) => {
                const col: any = {
                  label: column.fieldNameChn,
                  name: column.fieldName,
                  table: list[0]?.tableName,
                  xtype: column.controlType,
                };
                setTableColumnFormat(col, {
                  xtype: column.controlType,
                  options: column.enumValue?.split(';').map((item) => {
                    const vl = item.split('|');
                    return { value: isNumberType(column.fieldDbType) ? Number(vl[0]) : vl[0], label: vl[1] };
                  })
                });
                return col;
              })
          : [],
      tableProps: {
        showRowNumber: true,
        autoLoad: false,
        rowSelection: {
          type: [TableSelectionModel.MULTIPLE_INTERVAL, TableSelectionModel.CHECKBOX],
          keyField: 'id'
        },
        pagination: true
      }
    }]
  };
}

function getEditTpl(busType: string, mainTable: ITable[], detailTable: ITable[], templateInfo: any) {
  const panelTable:ITable[] = mainTable.slice();
  const tabsTable:ITable[] = [];
  
  //如果只有主表展示, 先把子表清空
  if(templateInfo.editLayout == ENUM_TEMPLATE.MAIN) {
    detailTable = [];
  }

  if(templateInfo.editDisplayType == EDIT_DISPLAY_TYPE.PANEL) {
    panelTable.push(...detailTable);
  }else{
    tabsTable.push(...detailTable);
  }
  return {
    type: 'detail-page',
    busType,
    masterTableName: mainTable[0]?.tableName,
    requestDetail: {
      method: 'get',
      url: '/customForm/customPC/getInfo'
    },
    requestSave: {
      method: 'post',
      url: '/customForm/customPC/save'
    },
    toolbar: [{
      type: 'tool-bar',
      buttonType: 'default',
      id: `${busType}_toolbar`,
      buttons: [
        {
          itemId: 'save',
          text: '保存',
          icon: 'SaveOutlined',
          itemType: 'primary'
        },
        {
          itemId: 'check',
          text: '送审',
          icon: 'SolutionOutlined'
        },
        {
          itemId: 'attachment',
          text: '附件',
          icon: 'PaperClipOutlined'
        },
        {
          itemType: 'divider'
        },
        {
          itemId: 'back',
          text: '返回',
          icon: 'ArrowLeftOutlined'
        }
      ]
    }],
    forms: panelTable.map((form) => ({
      type: 'udp-panel',
      title: form.tableNameChn || form.tableName,
      body: [{
        type: 'form',
        title: '',
        id: `${busType}_${form.tableName}`,
        name: form.tableName,
        table: form.tableName,
        wrapWithPanel: false,
        mode: 'horizontal',
        body: form.bizColumnDesignQueryVoList
          .filter(({ showFlg }) => showFlg === 1)
          .map((column) => ({
            ...getFormItemProps(column, form)
          }))
      }]
    })),
    tabs: [{
      type: 'tabs',
      removable: false,
      tabs: tabsTable.length == 0 ? [{title: '选项卡1', body: []}] : tabsTable.map((table) => ({
        title: table.tableNameChn,
        body: [
          {
            type: 'table',
            title: `table-${table.tableNameChn}`,
            id: `${busType}_${table.tableName}`,
            name: table.tableName,
            table: table.tableName,
            columnsTogglable: false,
            columns: table.bizColumnDesignQueryVoList
              .filter(({ showFlg }) => showFlg === 1)
              .map((column) => ({
                ...getFormItemProps(column, table)
              })),
            tableProps: {
              showRowNumber: {
                editOptions: {}
              },
              busKey: 'id'
            }
          }
        ]
      }))
    }]
  };
}

function getJsTpl() {
  return `$udp.AllReady(function () {
      console.log('detail Ready');
  }, function () {
      console.log('list Ready');
      $udp.request.on('request', function(url, options){
        //最终发送请求前的url和options
        return {
          url: url,
          options
        }
      });
      $udp.request.on('response', function(response, requestOptions, rawResponse){
        //接收到的response，请求的options，原始的response
        // console.log('[debug] response:', response, requestOptions, rawResponse);
        return response;
      });
  });`;
}

//可选能力，对应页面的toolbar按钮的配置
const CAPACITY_PAGE_BTN_MAP = {
  listTpl:{
    bizFlowFlag:[{
      "name": "push_bill",
      "itemId": "push_bill",
      "text": "生成目的单",
      "label": "生成目的单"
    }],
  },
  editTpl:{
    bizFlowFlag:[{
      "name": "quoteSrc",
      "itemId": "quoteSrc",
      "text": "引用来源",
      "icon": "FileAddOutlined",
      "label": "引用来源"
    }]
  }
}

//处理可选能力
function handleCapacity(capacity, tplMap){
  Object.keys(tplMap).forEach((tpl)=>{
    let tmpTpl = CAPACITY_PAGE_BTN_MAP[tpl];
    let tmpToolBar = tplMap[tpl]?.toolbar;    //TODO真奇怪，首次渲染时，toolbar是对象，保存一次后就成数组了
    let tmpBtns = (Array.isArray(tmpToolBar) ? tmpToolBar[0]?.buttons : tmpToolBar?.buttons) || [];

    Object.keys(CAPACITY_PAGE_BTN_MAP[tpl]).forEach((ii)=>{
      let tmpTargetBtn = tmpTpl[ii];
      if(capacity[ii] == 1){
        tmpTargetBtn.forEach((jj)=>{
          let tmpIndex = tmpBtns.findIndex((kk)=> kk.itemId == jj.itemId);
          if(tmpIndex == -1){
            tmpBtns.push(jj);
          }
        });
      }else{
        tmpTargetBtn.forEach((jj)=>{
          let tmpIndex = tmpBtns.findIndex((kk)=> kk.itemId == jj.itemId);
          if(tmpIndex > -1){
            tmpBtns.splice(tmpIndex, 1);
          }
        })
      }
    });
  })
}

export async function createContentTpl(busType: string, tables?: ITable[]) {
  const [mainTable, detailTable]: [ITable[], ITable[]] = [[], []];
  const content = await getDesignContent();
  console.log('[debug] createContentTpl:', content);
  tables?.forEach((table) => {
    table.tableType === 0 ? mainTable.push(table) : table.bizColumnDesignQueryVoList.length && detailTable.push(table);
  });
  const amisPackages = content.editInfo?.amisPackages || content.listInfo?.amisPackages;
  const packages = Object.keys(amisPackages || {}).length > 0 ? amisPackages : undefined;

  const listTpl = content.listInfo || getListTpl(busType, mainTable, content.templateInfo || {});
  const editTpl = content.editInfo || getEditTpl(busType, mainTable, detailTable, content.templateInfo || {});

  //历史数据兼容 begin
  listTpl.table = Array.isArray(listTpl.table) ? listTpl.table : [listTpl.table];
  listTpl.toolbar = Array.isArray(listTpl.toolbar) ? listTpl.toolbar : [listTpl.toolbar];
  editTpl.forms = Array.isArray(editTpl.forms) ? editTpl.forms : [editTpl.forms];
  editTpl.tabs = Array.isArray(editTpl.tabs) ? editTpl.tabs : [editTpl.tabs];
  editTpl.toolbar = Array.isArray(editTpl.toolbar) ? editTpl.toolbar : [editTpl.toolbar];
  //历史数据兼容 end


  handleCapacity(content.capacity || {}, { listTpl, editTpl });
  console.log('[debug] tpl:', listTpl, editTpl);

  return {
    listInfo: listTpl,
    editInfo: editTpl,
    jsInfo: content.jsInfo || getJsTpl(),
    recordVer: content.recordVer || 1,
    schemeName: content.schemeName,
    packages,
    id: content.id,
    loading: false
  };
}
